/*
 *      Fischer Chess Club
 *      Copyright (c) 2010 Ryan Chiu
 *      All rights reserved.
 *      
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fischer;

import java.net.Socket;
import java.io.DataInputStream;
import java.io.PrintStream;

public class ThreadHandler extends Thread {
	// Streams for connection
	public DataInputStream inp;
	public PrintStream outp;

	// Connection thread variables.
	public Socket socket;
	public static String[] usersonline = new String[1000];
	public static int n;
	public String username = "";

	public ThreadHandler(Socket s, int v) {
		socket = s;
		n = v;
	}

	@SuppressWarnings("deprecation")
	public void run() {
		try {
			inp = new DataInputStream(socket.getInputStream());
			outp = new PrintStream(socket.getOutputStream());

			Fischer.welcome(outp);
			outp.print("login: ");
			username = inp.readLine().toString().replaceAll("login: ", "");
			Authenticate.authenticate(username, inp, outp, socket);

			while (true) {
				String line = inp.readLine();
				// Listen to commands from user and take the appropriate
				// action(s).
				if (line.trim().equals("quit")) {
					Fischer.goodbye(outp);
					socket.close();
				} else if (Filter.hasBadWords(line)) {
					outp.println("That's a bozo no-no.");
					outp.print(Fischer.prompt);
				} else {
					outp.println(Command.parse(line, username));
					outp.print(Fischer.prompt);
				}
			}
		} catch (Exception e) {
			System.err.println("ThreadHandler Error: ");
			e.printStackTrace(System.err);
		}
	}
}
